package cn.com.yiqi.wsc.service.item.impl;

import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.item.AdminItemDao;
import cn.com.yiqi.wsc.dao.item.ItemCheckDao;
import cn.com.yiqi.wsc.dao.item.ItemTypeDao;
import cn.com.yiqi.wsc.dao.item.ItemTypePropertyDao;
import cn.com.yiqi.wsc.dao.item.criteria.ItemCheckCriteria;
import cn.com.yiqi.wsc.dao.item.criteria.ItemCriteria;
import cn.com.yiqi.wsc.dao.item.criteria.ItemTypeCriteria;
import cn.com.yiqi.wsc.dao.property.PropertyDao;
import cn.com.yiqi.wsc.entity.item.*;
import cn.com.yiqi.wsc.entity.property.Property;
import cn.com.yiqi.wsc.enumeration.*;
import cn.com.yiqi.wsc.service.check.CheckService;
import cn.com.yiqi.wsc.service.dictionary.DictionaryService;
import cn.com.yiqi.wsc.service.item.PortalItemService;
import cn.com.yiqi.wsc.service.item.enumerate.ItemKindEnum;
import cn.com.yiqi.wsc.service.user.UserService;
import cn.com.yiqi.wsc.util.SeqUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author 何刚
 * @ClassName: ${class}
 * @Description: TODO
 * @date 2017/3/6
 */
@Service
public class PortalItemServiceImpl implements PortalItemService {


    @Autowired
    private UserService userService;

    @Autowired
    private AdminItemDao adminItemDao;

    @Autowired
    private ItemTypeDao itemTypeDao;

    @Autowired
    private ItemTypePropertyDao itemTypePropertyDao;

    @Autowired
    private PropertyDao propertyDao;

    @Autowired
    private CheckService checkService;

    @Autowired
    private ItemCheckDao itemCheckDao;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    public Result<List<ItemTree>> tree() {

        Result result = new Result();

        List<ItemTree> itemTypes = itemTypeDao.getTree();

        //Id，ItemType
        Map<Integer, ItemTree> treeMap = new HashMap<>();

        List<ItemTree> options = new ArrayList<>();
        for (ItemTree itemTree : itemTypes) {

            treeMap.put(itemTree.getValue(), itemTree);

            if (itemTree.getPid() == 0) {
                //顶级
                options.add(itemTree);
            }

        }

        for (ItemTree itemType : itemTypes) {
            //通过PID去找到父级的ItemID
            Integer pid = itemType.getPid();

            if (pid != 0) {
                ItemTree itemTree = treeMap.get(pid);
                if (itemTree.getChildren() == null) {
                    itemTree.setChildren(new ArrayList<ItemTree>());
                    itemTree.getChildren().add(itemType);
                } else {
                    itemTree.getChildren().add(itemType);
                }
            }

        }

        result.setReturnValue(options);
        return result;
    }

    @Transactional
    @Override
    public Result insert(ItemDTO itemDTO, Integer userId) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        itemDTO.setInsertUserId(userId);
        itemDTO.setDelete(CommonEnum.PRESERVE.getValue());
        if (itemDTO.getKind() == ItemKindEnum.vip.getValue()) {
            itemDTO.setStatus(ItemStatusEnum.下架.getValue());
        } else {
            itemDTO.setStatus(ItemStatusEnum.待提交.getValue());
        }
        if (itemDTO.getKind() == ItemKindEnum.point.getValue()) {
            itemDTO.setPayType(2);
        }
        if (null == itemDTO.getPayType()) {
            itemDTO.setPayType(1);
        }
        itemDTO.setSoldCount(0);
        //默认值
        if (null == itemDTO.getStock()) {
            itemDTO.setStock(0);
        }
        //添加商品基本信息
        adminItemDao.insert(itemDTO);

        Integer itemId = itemDTO.getId();

        //缩略图
        ItemPicture itemPicture = new ItemPicture();
        itemPicture.setPicUrl(itemDTO.getThumbnail());
        itemPicture.setItemId(itemId);
        itemPicture.setInsertUserId(userId);
        itemPicture.setType(ItemPicEnum.THUMBNAIL.getValue());


        //预览图，详情图
        List<ItemPicture> itemPictureList = itemDTO.getItemPictures();

        if (itemPictureList == null) {
            itemPictureList = new ArrayList<>();
        } else {
            //设置userId
            for (ItemPicture pic : itemPictureList) {
                pic.setInsertUserId(userId);
                pic.setItemId(itemId);
            }

        }

        //添加缩略图
        itemPictureList.add(itemPicture);

        //添加图片
        adminItemDao.batchInsertItemPic(itemPictureList);

        //添加属性
        List<ItemPropertyDTO> itemProperties = itemDTO.getItemProperties();

        if (itemProperties != null) {
            for (ItemProperty property : itemProperties) {
                property.setInsertUserId(userId);
                property.setItemId(itemId);
            }
            adminItemDao.batchInsertItemProperty(itemProperties);
        }

        return result;
    }

    @Override
    public Result detail(ItemCriteria itemCriteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());


        Integer itemId = itemCriteria.getItemId();

        ItemDTO itemDTO = new ItemDTO();


        itemDTO = adminItemDao.getDetailByItemId(itemId);


        itemDTO.setTypeIds(SeqUtil.seq2List(itemDTO.getSeq() + itemDTO.getTypeId() + "."));

        List<ItemPicture> list = adminItemDao.getPictureByItemId(itemId);

        if (list != null && !list.isEmpty()) {


            Iterator<ItemPicture> iterator = list.iterator();
            while (iterator.hasNext()) {
                ItemPicture picture = iterator.next();
                if (ItemPicEnum.THUMBNAIL.getValue().equals(picture.getType())) {
                    itemDTO.setThumbnail(picture.getPicUrl());
                    iterator.remove();
                    break;
                }
            }

        }


        itemDTO.setItemPictures(list);

        itemDTO.setItemProperties(adminItemDao.getPropertyByItemId(itemId));

        result.putData("detail", itemDTO);

        return result;

    }

    @Transactional
    @Override
    public Result update(ItemDTO itemDTO, Integer userId) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        itemDTO.setUpdateUserId(userId);

        if (itemDTO.getKind() == ItemKindEnum.vip.getValue()) {
            itemDTO.setStatus(ItemStatusEnum.下架.getValue());
        } else {
            itemDTO.setStatus(ItemStatusEnum.待提交.getValue());
        }

        adminItemDao.update(itemDTO);

        //修改就是把之前的全部干掉。重新添加
        //删除之前的属性，图片
        Integer itemId = itemDTO.getId();
        adminItemDao.deleteItemPicByItemId(itemId);
        adminItemDao.deleteItemPropertyByItemId(itemId);

        //重新插入
        //缩略图
        ItemPicture itemPicture = new ItemPicture();
        itemPicture.setPicUrl(itemDTO.getThumbnail());
        itemPicture.setItemId(itemId);
        itemPicture.setInsertUserId(userId);
        itemPicture.setType(ItemPicEnum.THUMBNAIL.getValue());


        //预览图，详情图
        List<ItemPicture> itemPictureList = itemDTO.getItemPictures();

        if (itemPictureList == null) {
            itemPictureList = new ArrayList<>();
        } else {
            //设置userId
            for (ItemPicture pic : itemPictureList) {
                pic.setItemId(itemId);
                pic.setInsertUserId(userId);
            }

        }

        //添加缩略图
        itemPictureList.add(itemPicture);

        //添加图片
        adminItemDao.batchInsertItemPic(itemPictureList);

        //添加属性
        List<ItemPropertyDTO> itemProperties = itemDTO.getItemProperties();

        if (itemProperties != null) {
            for (ItemProperty property : itemProperties) {
                property.setInsertUserId(userId);
                property.setItemId(itemId);
            }
            adminItemDao.batchInsertItemProperty(itemProperties);
        }

        return result;
    }

    @Override
    public Result submit(ItemDTO itemDTO, Integer userId) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        Item itemForDelete = new ItemDTO();
        itemForDelete.setId(itemDTO.getId());
        itemForDelete.setStatus(ItemStatusEnum.待审核.getValue());
        adminItemDao.update(itemForDelete);

        return result;
    }

    @Override
    public Result delete(Item item) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        Item itemForDelete = new ItemDTO();
        itemForDelete.setId(item.getId());
        itemForDelete.setDelete(CommonEnum.DELETED.getValue());
        adminItemDao.update(itemForDelete);

        return result;
    }

    @Override
    public Result pageList(ItemCriteria criteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        if (!criteria.isGetAll()) {
            //如果不是所有 分页
            PageHelper.startPage(criteria.getCurrentPage(), criteria.getPageSize());
        }

        Integer typeId = criteria.getTypeId();
        if (typeId != null) {
            String seq = itemTypeDao.getSeqByTypeId(criteria.getTypeId());
            criteria.setSeq(seq + criteria.getTypeId() + ".");
        }
        PageHelper.orderBy("mi.d_insert_time DESC");

        PageInfo<ItemDTO> pageInfo = new PageInfo<>(adminItemDao.pageList(criteria));

        if (ItemKindEnum.vip.getValue().equals(criteria.getKind())) {
            //vip
            List<ItemDTO> itemDTOList = pageInfo.getList();

            if (!CollectionUtils.isEmpty(itemDTOList)) {

                //获取字典对应的标记
                Map<String, String> map = dictionaryService.getMapByCode(DictionaryCode.MS_ITEM_EXPIRE_TYPE.getCode());

                for (ItemDTO itemDTO : itemDTOList) {
                    String expire = itemDTO.getExpiry();
                    String[] arr = expire.split(":");
                    if (arr != null && arr.length == 2) {
                        itemDTO.setExpiryType(arr[1]);
                        itemDTO.setExpiryTypeName(map.get(arr[1]));
                        itemDTO.setExpiryValue(arr[0]);
                    }
                }
            }

            result.putData("list", itemDTOList);
        } else {
            result.putData("list", pageInfo.getList());
        }


        result.putData("total", pageInfo.getTotal());

        return result;
    }

    @Override
    public Result insertType(ItemType itemType) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        wrapSeq(itemType);

        itemTypeDao.insert(itemType);

        return result;
    }

    @Override
    public Result updateType(ItemType itemType) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());


        wrapSeq(itemType);


        itemTypeDao.update(itemType);

        return result;
    }

    private void wrapSeq(ItemType itemType) {
        if (itemType.getPid() != 0) {

            ItemType itemTypeForGet = new ItemType();
            itemTypeForGet.setId(itemType.getPid());

            itemTypeForGet = itemTypeDao.get(itemTypeForGet);

            itemType.setType(itemTypeForGet.getType());
            itemType.setSeq(itemTypeForGet.getSeq() + itemTypeForGet.getId() + ".");

        } else {

            itemType.setSeq("." + 0 + ".");

        }
    }

    @Override
    public Result deleteType(ItemType itemType) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        itemTypeDao.delete(itemType);

        return result;
    }

    @Override
    public Result getItemTypeByPid(ItemTypeCriteria criteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        result.putData("list", itemTypeDao.getItemTypeByPid(criteria));

        return result;
    }

    @Transactional
    @Override
    public Result propertyInsert(ItemTypePropertyAdminDTO itemTypePropertyAdminDTO) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        Property property = new Property();

        Integer userId = userService.getCurrentUserId();

        property.setName(itemTypePropertyAdminDTO.getName());
        property.setType(PropertyTypeEnum.PRODUCT_PROPERTY.getValue());
        property.setKind(PropertyKindEnum.TEXT.getValue());
        property.setInsertUserId(userId);

        propertyDao.insert(property);


        ItemTypeProperty itemTypeProperty = new ItemTypeProperty();
        itemTypeProperty.setInsertUserId(userId);
        itemTypeProperty.setPropertyId(property.getId());
        itemTypeProperty.setTypeId(itemTypePropertyAdminDTO.getTypeId());
        itemTypeProperty.setRequire(itemTypePropertyAdminDTO.getRequire());

        itemTypePropertyDao.insert(itemTypeProperty);

        return result;
    }

    @Transactional
    @Override
    public Result propertyUpdate(ItemTypePropertyAdminDTO itemTypePropertyAdminDTO) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        Integer userId = userService.getCurrentUserId();

        Property property = new Property();

        property.setUpdateUserId(userId);
        property.setName(itemTypePropertyAdminDTO.getName());
        property.setId(itemTypePropertyAdminDTO.getPropertyId());

        propertyDao.update(property);

        ItemTypeProperty itemTypeProperty = new ItemTypeProperty();

        itemTypeProperty.setId(itemTypePropertyAdminDTO.getId());
        itemTypeProperty.setRequire(itemTypePropertyAdminDTO.getRequire());

        itemTypePropertyDao.update(itemTypeProperty);

        return result;
    }

    @Transactional
    @Override
    public Result propertyDelete(ItemTypePropertyAdminDTO itemTypePropertyAdminDTO) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        ItemTypeProperty itemTypeProperty = new ItemTypeProperty();
        itemTypeProperty.setId(itemTypeProperty.getId());

        itemTypePropertyDao.delete(itemTypeProperty);


        Property property = new Property();

        property.setId(itemTypePropertyAdminDTO.getPropertyId());

        propertyDao.delete(property);

        return result;
    }

    @Override
    public Result getItemTypePropertyByItemTypeId(ItemTypeCriteria criteria) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        result.putData("list", itemTypePropertyDao.getItemTypePropertyByItemTypeId(criteria.getTypeId()));

        return result;
    }

    @Transactional
    @Override
    public Result checkItem(ItemCheck itemCheck, Integer userId) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        Item item = new Item();

        //修改分销金额
        item.setId(itemCheck.getContentId());

        if (CheckResultEnum.ACCESS.getValue().equals(itemCheck.getCheckResult())) {
            if (itemCheck.getSpreadSale() == null) {
                return ResultUtil.paramError(result, "请填写分销金额");
            }
            item.setSpreadSale(itemCheck.getSpreadSale());

            item.setStatus(ItemStatusEnum.上架.getValue());
        } else {
            item.setStatus(ItemStatusEnum.审核不通过.getValue());
        }


        adminItemDao.update(item);

        itemCheck.setContentType(CheckTypeEnum.ITEM.getValue());

        checkService.insertCheck(itemCheck);


        return result;
    }

    @Override
    public Result checkList(ItemCheckCriteria itemCheckCriteria) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        PageHelper.startPage(itemCheckCriteria.getCurrentPage(), itemCheckCriteria.getPageSize());
        PageHelper.orderBy("mc.d_insert_time DESC");

        PageInfo<ItemCheck> itemCheckPageInfo = new PageInfo<>(itemCheckDao.pageList(itemCheckCriteria));

        result.putData("list", itemCheckPageInfo.getList());

        result.putData("total", itemCheckPageInfo.getTotal());

        return result;
    }

    @Override
    public Result getItemTypePropertyByItemTypeSeq(ItemTypeCriteria criteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        result.putData("list", itemTypePropertyDao.getItemTypePropertyByItemTypeSeq(criteria.getTypeIds()));

        return result;
    }

    @Override
    public String getSeqByTypeId(Integer itemId) {

        return itemTypeDao.getSeqByTypeId(itemId);

    }

    @Override
    public Result onLine(ItemDTO itemDTO, Integer currentUserId) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        itemDTO.setStatus(ItemStatusEnum.上架.getValue());

        adminItemDao.update(itemDTO);

        return result;
    }

    @Override
    public Result offLine(ItemDTO itemDTO, Integer currentUserId) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        itemDTO.setStatus(ItemStatusEnum.下架.getValue());

        adminItemDao.update(itemDTO);

        return result;
    }

    @Override
    public ItemStatusEnum getStatusByItemId(Integer itemId) {

        Integer status = adminItemDao.getStatusByItemId(itemId);

        if (status != null) {
            return ItemStatusEnum.getStatusByValue(status);
        }

        return null;
    }

    @Override
    public List<ItemDTO> outPutItemList(ItemCriteria criteria) {
        List<ItemDTO> itemList = adminItemDao.pageList(criteria);

        return itemList;
    }

    @Override
    public boolean isServiceItem(Integer typeId) {

        String seq = getSeqByTypeId(typeId);

        //如果包含 .11. 则是服务类型
        return seq.contains("." + ItemTypeId.SERVICE.getId() + ".");

    }

}
